package com.eidetic.storage;

import java.util.Collection;

import com.eidetic.note.INote;
import com.eidetic.note.INoteStore;
import com.eidetic.storage.db.IStorageAdaptor;
import com.eidetic.util.INoteListener;

public class NoteStore implements INoteStore, INoteListener
{
	private Collection<INote> 		notes;
	private IStorageAdaptor<INote> 	noteAdaptor;
	
	public NoteStore(IStorageAdaptor<INote> noteAdaptor)
	{
		this.noteAdaptor = noteAdaptor;
		notes = noteAdaptor.fetchAll();
		// TODO Add tagging framework
		// TODO Add service sharing framework
	}
	
	@Override
	public Collection<INote> getNotes()
	{
		return notes;
	}

	@Override
	public void addNote(INote note)
	{
		notes.add(note);
		writeNote(note);
		note.registerListener(this);
	}

	@Override
	public void removeNote(INote note)
	{
		notes.remove(note);
		note.deleteListener(this);
		noteAdaptor.delete(note);
		
		if (note.getPhoto().exists())
			note.getPhoto().delete();
	}
	
	@Override
	public void onChanged(INote note)
	{
		writeNote(note);
	}

	private void writeNote(INote note)
	{
		if (note.getId() != -1)
			noteAdaptor.update(note);
		
		else
			noteAdaptor.create(note);
	}
}
